var express = require('express');
var router = express.Router();
var db = require('../sql')
let bodyParser = require("body-parser")
let server = express();
var jifen = require('../util/updateJiFeng');

function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}


/* GET users listing. */
// 1.获取所有用户信息
router.get('/allUser', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  db.query('select * from user', function (err, data) {
    res.send(data);
  })
});

// 2.获取所有订单信息
router.get('/order', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  db.query('select * from `userorder`', function (err, data) {
    res.send(data);
  })
});

// 3.添加新用户
server.use(bodyParser.urlencoded({ extended: true }))
// 将数据转换为json格式
server.use(bodyParser.json())
router.post('/checkUser', function (req, res) {
  console.log(req.body)
  let obj = req.body;
  db.query('INSERT INTO user VALUES(?,?,?,?,?)', [obj.openid, obj.nikename, obj.avatarUrl, obj.gender, obj.language], function (err, data) {
    try {
      res.send(data);
    } catch (err) {
      throw err
    }
  })
})

// 4.验证后台管理员账号密码
router.post('/checkAdmin', function (req, res) {
  let { name, password } = req.body;
  db.query('select * from admin where name=? and password=?', [name, password], function (err, data) {
    if (err) {
      throw err
    } else {
      if (data.length) {
        res.send({ msg: '查询成功', code: 200, shopid: data[0].shopid })
      } else {
        res.send({ msg: '查询失败', code: 404 })
      }
    }
  })
})

// 5.获取用户信息
router.get('/getUserInfo', function (req, res) {
  let { openid } = req.query;
  db.query('select * from user where openid=?', [openid], function (err, data) {
    if (err) {
      throw err
    } else {
      if (data.length) {
        res.send({ msg: '查询成功', code: 200, data })
      } else {
        res.send({ msg: '查询失败', code: 404 })
      }
    }
  })
})

// 6.获取用户的积分明细
router.get('/getUserintegralrecord', function (req, res) {
  let { openid } = req.query;
  db.query('select * from integralrecord where openid=? ORDER BY addtime DESC', [openid], function (err, data) {
    if (err) {
      throw err
    } else {
      if (data.length) {
        res.send({ msg: '查询成功', code: 200, data })
      } else {
        res.send({ msg: '查询失败', code: 404 })
      }
    }
  })
})

// 7.获取所有优惠券
router.get('/getCoupon', function (req, res) {
  db.query('select * from coupon ', [], function (err, data) {
    if (err) {
      throw err
    } else {
      if (data.length) {
        res.send({ msg: '查询成功', code: 200, data })
      } else {
        res.send({ msg: '查询失败', code: 404 })
      }
    }
  })
})

// 8.兑换优惠券，并且克扣积分
router.post('/addUserCoupon', function (req, res) {
  let obj = req.body;
  // 查找是否有该优惠券
  db.query('select * from usercoupon where couponid=? and userid=?', [obj.couponid, obj.userid], function (err, data) {
    if (err) {
      throw err
    } else {
      // 如果有则更新数量
      if (data.length >= 1) {
        db.query('UPDATE usercoupon SET num=?  where couponid=? and userid=?', [data[0].num + 1, obj.couponid, obj.userid],
          async function (err, data) {
            if (err) {
              throw err
            } {
              // 第一步：获取用户积分
              const userJiFeng = new Promise((resolve, reject) => {
                db.query('select * from user where openid=?', [obj.userid], function (err, data) {
                  if (err) {
                    reject(err)
                  } else {
                    resolve(data)
                  }
                })
              })
              const JiFengdata = await userJiFeng;
              console.log("获取到用户积分了", '当前积分', JiFengdata[0].nowIntegral);
              // 第二步：消耗用户积分 
              const consumePoints = new Promise((resolve, reject) => {
                nowIntegral = JiFengdata[0].nowIntegral - obj.price;
                db.query('update `user` set nowIntegral=? where openid=?', [nowIntegral, obj.userid], function (err, data) {
                  if (err) {
                    reject(err);
                  } else {
                    resolve(data);
                  }
                })
              })
              await consumePoints;
              // 第三步：添加积分消耗记录
              jifen.JiFengRecord({
                msg: "兑换优惠券",
                status: 2,
                Integral: obj.price,
                openid: obj.userid
              });
              res.send({ "msg": "兑换成功", data });
            }
          })
        // 如果没有则插入
      } else {
        db.query('INSERT INTO usercoupon (couponid,userid,num) VALUES(?,?,?)', [obj.couponid, obj.userid, obj.num],
          async function (err, data) {
            if (err) {
              throw err
            } {
              // 第一步：获取用户积分
              const userJiFeng = new Promise((resolve, reject) => {
                db.query('select * from user where openid=?', [obj.userid], function (err, data) {
                  if (err) {
                    reject(err)
                  } else {
                    resolve(data)
                  }
                })
              })
              const JiFengdata = await userJiFeng;
              console.log("获取到用户积分了", '当前积分', JiFengdata[0].nowIntegral);
              // 第二步：消耗用户积分 
              const consumePoints = new Promise((resolve, reject) => {
                nowIntegral = JiFengdata[0].nowIntegral - obj.price;
                db.query('update `user` set nowIntegral=? where openid=?', [nowIntegral, obj.userid], function (err, data) {
                  if (err) {
                    reject(err);
                  } else {
                    resolve(data);
                  }
                })
              })
              await consumePoints;
              // 第三步：添加积分消耗记录
              jifen.JiFengRecord({
                msg: "兑换优惠券",
                status: 2,
                Integral: obj.price,
                openid: obj.userid
              });
              res.send({ "msg": "兑换成功", data });
            }
          })
      }
    }
  })
})

// 9.获取指定用户的优惠券
router.get('/getUserCoupon', async function (req, res) {
  let obj = req.query;
  const coupons = new Promise((resolve, reject) => {
    db.query('select * from usercoupon where userid=?', [obj.userid], function (err, data) {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
  const resss = await coupons;
  for (let i = 0; i < resss.length; i++) {
    const COUPON = new Promise((resolve, reject) => {
      db.query('select * from coupon where id=?', [resss[i].couponid], function (err, data) {
        if (err) {
          reject(err)
        } else {
          resolve(data)
        }
      })
    })
    const COU2 = await COUPON;
    resss[i] = { ...resss[i], ...COU2[0] }
  }
  res.send(resss);
})

// 10.更新优惠价数量
router.get('/ChangeUserCoupon', async function (req, res) {
  let obj = req.query;
  db.query('UPDATE usercoupon SET num=?  where couponid=? and userid=?', [obj.num - 1, obj.couponid, obj.userid],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send(data)
      }
    })
})

// 11.获取所有优惠券
// router.get('/getCoupon',function (req, res) {
//     db.query('select * from coupon', function (err, data) {
//       if(err){
//         throw err
//       }else{
//         res.send(data)
//       }
//     })
// })

// 12.添加优惠券
router.post('/addCoupon', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { price, name, discountmoney } = req.body;
  db.query(`insert into coupon (price,name,discountmoney) 
  values (?,?,?)`,
    [price, name, discountmoney],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ code: 200, msg: "添加成功", data });
      }
    })
})

// 13.删除优惠券
router.get('/deleteCouponData', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  const { id } = req.query;
  db.query('delete from coupon where id=?', [id], function (err, data) {
    if (err) {
      throw err
    } else {
      res.send(data);
    }
  })
});

// 14.修改优惠券
router.get('/ChangeCoupon', async function (req, res) {
  let { price, name, discountmoney, id } = req.query;
  price = Number(price)
  discountmoney = Number(discountmoney)
  id = Number(id)
  console.log(price, name, discountmoney, id);
  db.query('UPDATE coupon SET price=? , name=? , discountmoney=? where id=?', [price, name, discountmoney, id],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ code: 200, data })
      }
    })
})

// 提交订单第二版：
router.post('/addUserOrder', async function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { userid, shopid, status, msg = "", discount, sumPrice, sumCount, tackTime, selectShopCar } = req.body;
  if (!discount) discount = 0
  const orderid = guid();
  const id = Math.floor(Math.random()*200);
  const OrderRes = await new Promise((resolve, reject) => {
    db.query(`insert into userorder (userid,shopid,orderid,status,msg,discount,sumPrice,sumCount,tackTime,tackid) 
  values (?,?,?,?,?,?,?,?,?,?)`,
      [userid, shopid, orderid, status, msg, discount, sumPrice, sumCount, tackTime,id],
      function (err, data) {
        if (err) {
          reject(err)
        } else {
          resolve({ code: 200, msg: "添加成功", data });
        }
      })
  })
  console.log("============================");
  // 插入订单数据成功
  console.log('订单情况', OrderRes);
  if (OrderRes.code == 200) {
    // 插入所有购物车的商品
    for (let item of selectShopCar) {
      console.log('申请', item)
    }
    selectShopCar.forEach(async n => {
      const { _id, shopid, icon, name, price, sell, status, _createTime, _updateTime, fenlei, num, label } = n
      await new Promise((resolve, reject) => {
        db.query(`insert into userorderfoodlist (
          orderid,_id,shopid,icon,name,price,sell,status,_createTime,_updateTime,fenlei,num,label) 
      values (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
          [orderid, _id, shopid, icon, name, price, sell, status, _createTime, _updateTime, fenlei, num, JSON.stringify(label)],
          function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve({ code: 200, msg: "添加成功", data });
            }
          })
      })
    });
    res.send({ code: 200, msg: "更新/添加订单成功" })
  }
})

// 获取订单第二版:
router.get('/getUserOrder', async function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { userid } = req.query;
  const OrderRes = await new Promise((resolve, reject) => {
    db.query(`select * from userorder where userid=? order by createTime desc`
      , userid,
      function (err, data) {
        if (err) {
          reject(err)
        } else {
          resolve({ code: 200, msg: "获取成功", data });
        }
      })
  })
  // 获取订单数据成功
  if (OrderRes.code == 200) {



    for (let i in OrderRes.data) {
      // OrderRes.data[i].name ="龙岩学院4组4分店"
      console.log(OrderRes.data[i].shopid);
      // await new Promise((resolve, reject) => {
        db.query(`select * from shop where id=?`, [OrderRes.data[i].shopid],
          function (err, data) {
            if (err) {
              reject(err)
            } else {
              console.log("data",data);
              OrderRes.data[i].name = data[0].name;
              OrderRes.data[i].address = data[0].address
            }
          })
      // });
    }


    
    for (let n of OrderRes.data) {
      const foodRes = await new Promise((resolve, reject) => {
        db.query(`select * from userorderfoodlist where orderid=?`, [n.orderid],
          function (err, data) {
            if (err) {
              reject(err)
            } else {
              resolve({ code: 200, msg: "获取成功", data });
            }
          })
      });
      const food = foodRes.data.map(n => {
        return {
          ...n,
          label: JSON.parse(n.label)
        }
      })
      n.selectShopCar = food
    }
    // 获取所有订单的商品
    console.log('2323',OrderRes.data)
    res.send({ code: 200, msg: "更新/添加订单成功", data:OrderRes.data })
  }
})

// 增加管理员
router.post('/addAdimin', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { shopid,name,password } = req.body;
  console.log(req.body)
  db.query(`insert into admin (shopid,name,password) 
  values (?,?,?)`,
    [shopid,name,password],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ code: 200, msg: "添加成功", data });
      }
    })
})

// 修改管理员
router.post('/updateAdimin', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { shopid,name,password } = req.body;
  console.log(shopid,name,password,'数据');
  console.log(req.body)
  db.query(`UPDATE admin SET name=? ,password=? where shopid=?`,
    [name,password,shopid],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ code: 200, msg: "添加成功", data });
      }
    })
})

// 增加标签
router.post('/addFoodLabel', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  let { text,type,ischeck =0 } = req.body;
  db.query(`insert into foodlabel (text,type,ischeck) 
  values (?,?,?)`,
    [text,type,ischeck],
    function (err, data) {
      if (err) {
        throw err
      } else {
        res.send({ code: 200, msg: "添加成功", data });
      }
    })
})
module.exports = router;
